<?php

namespace app\data\command;

use app\admin\service\FeiShuService;
use app\admin\service\WxWorkService;
use app\data\service\AliSingleCallService;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;
use think\db\exception\DbException;
use think\facade\Log;

/**
 * 聊天记录解析
 * Class MessageParse
 * @package app\data\command
 */
class NotCompleteRecordNotify extends Command
{
    protected function configure()
    {
        $this->setName('not_complete_record_notify');
        $this->setDescription('每日未完成订单提醒');
    }

    /**
     * 每日未完成订单提醒
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $today = date('Y-m-d 00:00:00');
        Log::info('每日未完成订单提醒-' . $today);

        $records = $this->app->db->name('data_record')->whereIn('paint_status', [-1, 0])->where('time_docking', '>=', $today)->select()->toArray();
        if (!empty($records)) {
            $uuidCityUserIds = array_column($records, 'uuid_city');
            $users = $this->app->db->name('work_user')->whereIn('id', $uuidCityUserIds)->field('open_id,id')->select()->toArray();
            foreach ($users as $user) {
                $mapId2WorkUserId[$user['id']] = $user['open_id'];
                $mapId2WorkUserMobile[$user['id']] = $user['mobile'];
            }


            foreach ($records as $record) {
                $message = "{$record['id']} {$record['plate_number']}，暂未进行完成工单，请确认；";
                $openId = $mapId2WorkUserId[$record['uuid_city']] ?? 0;
                $mobile = $mapId2WorkUserMobile[$record['uuid_city']] ?? 0;
                if ($openId) {
                    try {
                        FeiShuService::instance()->sendMessageTextByUserid($openId, $message);
                    } catch (\Exception $exception) {
                        Log::error('每日未完成订单企业微信提醒报错 ' . $exception->getMessage());
                    }
                }
                if ($mobile) {
                    try {
                        AliSingleCallService::singleCallByTts($mobile, 'TTS_287015060', ['plateNumber' => $record['plate_number']]);
                    } catch (\Exception $exception) {
                        Log::error('每日未完成订单语音提醒报错 ' . $exception->getMessage());
                    }
                }
            }
        }
    }

}